package com.example.controller;

import com.example.common.response.Result;
import com.example.model.dto.AuthRequest;
import com.example.model.dto.AuthResponse;
import com.example.model.dto.UserRegisterRequest;
import com.example.model.entity.User;
import com.example.security.JwtTokenUtil;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result<AuthResponse> login(@Valid @RequestBody AuthRequest request) {
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
        );

        final UserDetails userDetails = userService.loadUserByUsername(request.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);

        return Result.success(new AuthResponse(token));
    }

    @PostMapping("/register")
    public Result<AuthResponse> register(@Valid @RequestBody UserRegisterRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setNickname(request.getNickname());
        user.setEmail(request.getEmail());

        User savedUser = userService.register(user);
        
        final UserDetails userDetails = userService.loadUserByUsername(savedUser.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);

        return Result.success(new AuthResponse(token));
    }
} 